var async = require("async")
var UUID = require("uuid");
var util = require("../../../util/util.js")
module.exports = function(app) {
	return new DBRemote(app);
};

var DBRemote = function(app) {
	this.app = app
	DBRemote.app = app
    DBRemote.dbService = this.app.get("dbService")
}

var local = {}

//申请提现
DBRemote.prototype.applyWithdrawal = function(uid,value,cb) {
	if(!value || typeof(value) != "number" || value <= 0){
		cb(false)
		return
	}
	value = parseFloat(value.toFixed(2))
	DBRemote.dbService.getItem(uid,104,function(data) {
		if(data != 0){
			cb(false,"已申请")
			return
		}else{
			DBRemote.dbService.addItemReason(uid,103,-value,"提现冻结",function(flag,curValue) {
				if(flag){
					if(curValue >= 0){
						var messageInfo = {
							messageType : "withdrawal",
							uid : uid,
							value : value,
							curValue : curValue,
							ID : UUID.v1(),
							time : (new Date()).getTime()
						}
						DBRemote.dbService.writeMessage(JSON.stringify(messageInfo))
						DBRemote.dbService.addItem(uid,104,value,function() {
							cb(true)
						})
					}else{
						DBRemote.dbService.addItemReason(uid,103,value,"冻结返还")
						cb(false)
					}
				}else{
					cb(false)
				}
			})
		}
	})
}
//提现成功
DBRemote.prototype.applySuccess = function(uid,cb) {
	DBRemote.dbService.getItem(uid,104,function(data) {
		if(data){
			data = parseFloat(data)
			DBRemote.dbService.addItemReason(uid,104,-data,"提现成功")
			var mailInfo = {
				uid : uid,
				title : "提现成功",
				content : "您的提现申请已通过，红包已发放到您的微信账号，余额账单可以到个人中心查看。如若遇到提现未到账等情况请联系客服",
				award : false
			}
			DBRemote.dbService.app.rpc.db.mail.sendMail(null,mailInfo.uid,mailInfo.title,mailInfo.content,mailInfo.award,function(flag) {})
			var info = {
				time : (new Date()).getTime(),
				value : data,
				state : true
			}
			DBRemote.dbService.db.rpush("game:withdrawalRecords:"+uid,JSON.stringify(info))
			cb(true)
		}else{
			cb(false,"未申请提现")
		}
	})
}
//提现失败
DBRemote.prototype.applyReject = function(uid,cb) {
	DBRemote.dbService.getItem(uid,104,function(data) {
		if(data){
			data = parseFloat(data)
			DBRemote.dbService.addItemReason(uid,104,-data,"拒绝提现")
			DBRemote.dbService.addItemReason(uid,103,data,"拒绝提现")
			var mailInfo = {
				uid : uid,
				title : "提现被拒绝",
				content : "您的提现申请已被拒绝，请前往提现中心查看具体原因",
				award : false
			}
			DBRemote.dbService.app.rpc.db.mail.sendMail(null,mailInfo.uid,mailInfo.title,mailInfo.content,mailInfo.award,function(flag) {})
			var info = {
				time : (new Date()).getTime(),
				value : data,
				state : false
			}
			DBRemote.dbService.db.rpush("game:withdrawalRecords:"+uid,JSON.stringify(info))
			cb(true)
		}else{
			cb(false,"未申请提现")
		}
	})
}